package com.baozun.houji.goods.widget

import android.content.Context
import android.content.res.TypedArray
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.graphics.drawable.ShapeDrawable
import android.graphics.drawable.shapes.PathShape
import android.util.AttributeSet
import android.view.View
import androidx.core.content.ContextCompat
import com.baozun.houji.goods.R
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.SizeUtils
import kotlin.math.abs

/**
 * @Title：数字进度条view
 * @Description：
 * @Author：xuefeng.zhu
 * @Since：2023/12/4
 * @Version：1.0.0
 */
class NumberProgressBarView(context: Context?, attr: AttributeSet?) : View(context, attr) {

    private var mDefaultWidth = 0  //默认宽度
    private var mDefaultHeight = 0 //默认高度
    private var mDefaultTextMargin = 0 //默认文本与进度的高度
    private var mTotalsCount = 0 //总长度

    private var mTextPaint: Paint = Paint()
    private var mLeftProgress = 0
    private var mProgressHeight = 0f
    private var isAllProgressZero: Boolean = false
    private var mCanvas: Canvas? = null

    init {

        //初始化属性
        val mTypedArray: TypedArray = context!!.obtainStyledAttributes(
            attr,
            R.styleable.NumberProgressView
        )
        mTotalsCount = mTypedArray.getInt(R.styleable.NumberProgressView_totalCount, -1)
        mLeftProgress = mTypedArray.getInt(R.styleable.NumberProgressView_leftProgress, -1)
        mProgressHeight = mTypedArray.getDimension(R.styleable.NumberProgressView_progressHeight, 6f)
        //设置抗锯齿
        mTextPaint.isAntiAlias = true
        //解决不能xml预览问题
        if (!isInEditMode) {
            mDefaultWidth = ScreenUtils.getAppScreenWidth()
            mDefaultHeight = SizeUtils.dp2px(20f)
            mDefaultTextMargin = SizeUtils.dp2px(2f)
            mTextPaint.textSize = SizeUtils.sp2px(11f).toFloat()
        }

    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        this.mCanvas = canvas
        drawProgressBg(canvas)
        drawLeftProgress(canvas)
        drawLeftText(canvas)
        drawRightText(canvas)
    }

    /**
     * 画进度条背景
     */
    private fun drawProgressBg(canvas: Canvas?) {
        var bgPath = Path()
        bgPath.moveTo(0f, height / 2 + mProgressHeight / 2)
        bgPath.lineTo(width.toFloat(), height / 2 + mProgressHeight / 2)
        bgPath.lineTo(
            width.toFloat(),
            height / 2 - mProgressHeight / 2
        )
        bgPath.lineTo(0f, height / 2 - mProgressHeight / 2)
        bgPath.close()
        var trapezoid = ShapeDrawable(PathShape(bgPath, width.toFloat(), mProgressHeight))
        trapezoid.paint.style = Paint.Style.FILL
        trapezoid.paint.strokeWidth = mProgressHeight
        trapezoid.paint.color = ContextCompat.getColor(context, com.baozhun.mall.res.R.color.color_B7B7B7)
        trapezoid.setBounds(0, 0, width, mProgressHeight.toInt())
        if (canvas != null) {
            trapezoid.draw(canvas)
        }
    }

    /**
     * 画左边进度，左边实际宽度为上面line的长度
     */
    private fun drawLeftProgress(canvas: Canvas?) {
        if (mLeftProgress == -1 || mTotalsCount == -1 || mTotalsCount == 0) return
        var leftWidth = mLeftProgress * (width / mTotalsCount.toFloat()) - mProgressHeight
        var leftPath = Path()
        //连线顺序为 左下-右下-右上-左上
        leftPath.moveTo(0f, height / 2 + mProgressHeight / 2)
        leftPath.lineTo(leftWidth, height / 2 + mProgressHeight / 2)
        //左边实际宽度:leftWidth + mProgressHeight
        leftPath.lineTo(
            leftWidth + mProgressHeight,
            height / 2 - mProgressHeight / 2
        )
        leftPath.lineTo(0f, height / 2 - mProgressHeight / 2)
        leftPath.close()
        var trapezoid = ShapeDrawable(PathShape(leftPath, leftWidth, mProgressHeight))
        trapezoid.paint.style = Paint.Style.FILL
        trapezoid.paint.strokeWidth = mProgressHeight
        trapezoid.paint.color = ContextCompat.getColor(context, com.baozhun.mall.res.R.color.color_FC2E24)
        trapezoid.setBounds(0, 0, leftWidth.toInt(), mProgressHeight.toInt())
        if (canvas != null) {
            trapezoid.draw(canvas)
        }
    }

    /**
     * 画左边文字
     */
    private fun drawLeftText(canvas: Canvas?) {
        if (mLeftProgress == -1 || mTotalsCount == -1 || mTotalsCount == 0) return
        mTextPaint.color = ContextCompat.getColor(
            context,
            if (mLeftProgress == 0) com.baozhun.mall.res.R.color.color_FC2E24 else com.baozhun.mall.res.R.color.color_FC2E24
        )
        mTextPaint.style = Paint.Style.FILL
        val fontMetrics: Paint.FontMetrics = mTextPaint.fontMetrics
        var leftText = if (isAllProgressZero) "0" else mLeftProgress.toString()
        var textWidth = mTextPaint.measureText(leftText)
//        var leftWidth = mLeftProgress * (width / mTotalsCount.toFloat())
        //需求变更，固定显示在左边
        var leftWidth = 0f
        //兼容左边宽度为0时文字显示不全问题；右边进度为0左边文字也显示在最左边
        leftWidth = if (leftWidth == 0f || mLeftProgress == mTotalsCount) textWidth else leftWidth
        var textX = leftWidth / 2 - textWidth / 2
        //获取基线y坐标
        var textHeight = fontMetrics.bottom - fontMetrics.top
        val baseline = (height - textHeight) / 2 + textHeight - fontMetrics.bottom - mProgressHeight - mDefaultTextMargin
        canvas?.drawText(leftText, textX, baseline, mTextPaint)
    }

    /**
     * 画右边文字
     */
    private fun drawRightText(canvas: Canvas?) {
        if (mLeftProgress == -1 || mTotalsCount == -1 || mTotalsCount == 0) return
        mTextPaint.color = ContextCompat.getColor(context, com.baozhun.mall.res.R.color.color_B7B7B7)
        mTextPaint.style = Paint.Style.FILL
        val fontMetrics: Paint.FontMetrics = mTextPaint.fontMetrics
        var textHeight = fontMetrics.bottom - fontMetrics.top

        var rightText = if (isAllProgressZero) "0" else (mTotalsCount - mLeftProgress).toString()
        var textWidth = mTextPaint.measureText(rightText)
//        var rightWidth = (mTotalsCount - mLeftProgress) * (width / mTotalsCount.toFloat())
        //需求变更，固定显示在右边
        var rightWidth = 0f
        //兼容右边为0时右边文字显示不全问题;当左边为0时右边文字显示在最右边
        rightWidth = if (rightWidth == 0f || mLeftProgress == 0) textWidth else rightWidth
        var textX = (width - rightWidth) + (width - (width - rightWidth)) / 2 - textWidth / 2
        val baseline = (height - textHeight) / 2 + textHeight - fontMetrics.bottom - mProgressHeight - mDefaultTextMargin
        canvas?.drawText(rightText, textX, baseline, mTextPaint)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        // 获取宽的测量模式
        val wSpecMode = MeasureSpec.getMode(widthMeasureSpec)
        // 获取符控件提供的 view 宽的最大值
        val wSpecSize = MeasureSpec.getSize(widthMeasureSpec)

        val hSpecMode = MeasureSpec.getMode(heightMeasureSpec)
        val hSpecSize = MeasureSpec.getSize(heightMeasureSpec)

        if (wSpecMode == MeasureSpec.AT_MOST && hSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(mDefaultWidth, mDefaultHeight)
        } else if (wSpecMode == MeasureSpec.AT_MOST) { //AT_MOST:WARP_CONTENT  EXACTLY:MATCH_PARENT
            setMeasuredDimension(mDefaultWidth, hSpecSize)
        } else if (hSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(wSpecSize, mDefaultHeight)
        } else {
            setMeasuredDimension(wSpecSize, hSpecSize)
        }
    }

    fun setProgress(leftProgress: Int?, totalsCount: Int?) {
        if (leftProgress != null && totalsCount != null) {
            this.mLeftProgress = abs(leftProgress)
            this.mTotalsCount = abs(totalsCount)
            if (leftProgress == 0 && totalsCount == 0) {
                isAllProgressZero = true
                mLeftProgress = 50
                mTotalsCount = 100
            } else {
                isAllProgressZero = false
            }
            invalidate()
        }
    }

}